package com.tcl.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author gaodp
 */
@Configuration
@EnableConfigurationProperties(HttpClientProperties.class)
@ConditionalOnClass(HttpClient.class)
public class HttpClientAutoConfiguration {

    private HttpClientProperties properties;

    @Autowired
    public HttpClientAutoConfiguration(HttpClientProperties properties) {
        this.properties = properties;
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(clientHttpRequestFactory());
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public CloseableHttpClient httpClient() {
        HttpClientProperties.Request request = properties.getRequest();
        return HttpClientBuilder
                .create()
                .setConnectionManager(httpClientConnectionManager())
                .setDefaultRequestConfig(RequestConfig
                        .custom()
                        .setConnectionRequestTimeout(request.getConnectionRequestTimeout())
                        .setConnectTimeout(request.getConnectTimeout())
                        .setSocketTimeout(request.getSocketTimeout())
                        .build())
                .build();
    }

    @Bean
    public HttpClientConnectionManager httpClientConnectionManager() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        HttpClientProperties.Connection connection = properties.getConnection();
        connectionManager.setMaxTotal(connection.getMaxTotal());
        connectionManager.setDefaultMaxPerRoute(connection.getDefaultMaxPerRoute());
        return connectionManager;
    }

}
